document.addEventListener('DOMContentLoaded', () => {
    // $.ajax({
    //     url: host + "/api/stock/warning",
    //     type: "get",
    //     success: function (res) {
    //         console.log(res)
    //         let arr = res.data
    //         let resArr = []
    //         arr.map(item => {
    //             console.log(item.df.trade_date.slice(-3)[0])
    //             let param = {
    //                 name: item.name,
    //                 code: item.code,
    //                 closePrice: item.df.close.slice(-4)[0],
    //                 highPrice: item.df.high.slice(-3)[0],
    //                 nextTradingDay: item.df.trade_date.slice(-3)[0],
    //                 lastTradingDay: item.df.trade_date.slice(-4)[0]
    //             }
    //             resArr.push(param)
    //         })
    //         dealWebData(resArr)//启动填充数据函数
    //
    //         //给显示的区域绑定鼠标事件
    //          $("#warning_content").bind("mouseover",function(){StopScroll1();});
    //          $("#warning_content").bind("mouseout",function(){StartScroll1();});
    //         //启动滚动定时器
    //          StartScroll1();
    //     }
    // })
    // 模拟从接口获取的数据
    const warning_stockData = [
        // { name: "Apple Inc.", code: "AAPL", closePrice: 150.00, highPrice: 155.00, nextTradingDay: "2024-06-12", lastTradingDay: "2024-06-11" },
        // { name: "Microsoft Corp.", code: "MSFT", closePrice: 250.00, highPrice: 260.00, nextTradingDay: "2024-06-12", lastTradingDay: "2024-06-11" },
        // { name: "Amazon.com Inc.", code: "AMZN", closePrice: 3300.00, highPrice: 3350.00, nextTradingDay: "2024-06-12", lastTradingDay: "2024-06-11" },
        // { name: "Alphabet Inc.", code: "GOOGL", closePrice: 2800.00, highPrice: 2850.00, nextTradingDay: "2024-06-12", lastTradingDay: "2024-06-11" },
        // { name: "Meta Platforms Inc.", code: "META", closePrice: 350.00, highPrice: 360.00, nextTradingDay: "2024-06-12", lastTradingDay: "2024-06-11" },
        // { name: "Tesla Inc.", code: "TSLA", closePrice: 700.00, highPrice: 720.00, nextTradingDay: "2024-06-12", lastTradingDay: "2024-06-11" },
        // { name: "NVIDIA Corp.", code: "NVDA", closePrice: 600.00, highPrice: 610.00, nextTradingDay: "2024-06-12", lastTradingDay: "2024-06-11" },
        // { name: "Netflix Inc.", code: "NFLX", closePrice: 500.00, highPrice: 510.00, nextTradingDay: "2024-06-12", lastTradingDay: "2024-06-11" },
        // { name: "Adobe Inc.", code: "ADBE", closePrice: 550.00, highPrice: 560.00, nextTradingDay: "2024-06-12", lastTradingDay: "2024-06-11" },
        // { name: "PayPal Holdings Inc.", code: "PYPL", closePrice: 270.00, highPrice: 280.00, nextTradingDay: "2024-06-12", lastTradingDay: "2024-06-11" }
    ];
    let resArr = []
    $.ajax({
        url: host + "/api/stock/warning",
        type: "get",
        success: function (res) {
            console.log(res)
            let arr = res.data
            arr.map(item => {
                if (item.warning === 1) {
                    warning_stockData.push({
                        name: item.name,
                        code: item.code,
                        closePrice: item.df.close.slice(-4)[0],
                        highPrice: item.df.high.slice(-3)[0],
                        nextTradingDay: item.df.trade_date.slice(-3)[0],
                        lastTradingDay: item.df.trade_date.slice(-4)[0]
                    })
                }
            })

            // warning_stockData.map(item => {
            //     // console.log(item.df.trade_date.slice(-3)[0])
            //     let param = {
            //         name: item.name,
            //         code: item.code,
            //         closePrice: item.closePrice,
            //         highPrice: item.highPrice,
            //         nextTradingDay: item.nextTradingDay.slice(-3)[0],
            //         lastTradingDay: item.lastTradingDay.slice(-4)[0]
            //     }
            //     resArr.push(param)
            // })

            resArr = [...warning_stockData]
            // dealWebData(resArr)//启动填充数据函数
            createAndFillStockBoxes(resArr); // 假设 resArr 已经是处理好的数据数组

            //给显示的区域绑定鼠标事件
            $("#warning_content").bind("mouseover",function(){StopScroll1();});
            $("#warning_content").bind("mouseout",function(){StartScroll1();});

            // 初始化计时器

        }
    })

    let timer = setInterval(checkData, 1000);

    // 检查数据的函数
    function checkData() {
        // 假设这是获取数据的函数，这里需要替换为实际的API调用
        const data = resArr;

        if (data) {
            // 如果数据已经到达，清除计时器并执行特定方法
            clearInterval(timer);
            //启动滚动定时器
            StartScroll1();
        }
    }

    function createAndFillStockBoxes(stockData) {
        const container_top = document.getElementById('warning_top');
        const container_bottom = document.getElementById('warning_bottom');
        const container_big = document.getElementById('warningContainer-big');
        // container.innerHTML = ''; // 清空现有内容

        stockData.forEach(stock => {
            // 创建新的 stock-box 元素
            const stockBox_top = document.createElement('div');
            stockBox_top.className = 'stock-box';
            const stockBox_bottom = document.createElement('div');
            stockBox_bottom.className = 'stock-box';
            const stockBox_big = document.createElement('div');
            stockBox_big.className = 'stock-box';

            // 格式化日期和价格
            const formattedNextTradingDay = formatDate(stock.nextTradingDay);
            const formattedLastTradingDay = formatDate(stock.lastTradingDay);

            // 设置 stock-box 内部的 HTML
            stockBox_top.innerHTML = `
            <div class="stock-info">${stock.name} (${stock.code})</div>
            <div class="stock-prices">${formattedLastTradingDay} 收盘价: ${stock.closePrice.toFixed(2)} | ${formattedNextTradingDay} 最高价: <span class="high-price">${stock.highPrice.toFixed(2)}</span></div>
        `;
            stockBox_bottom.innerHTML = `
            <div class="stock-info">${stock.name} (${stock.code})</div>
            <div class="stock-prices">${formattedLastTradingDay} 收盘价: ${stock.closePrice.toFixed(2)} | ${formattedNextTradingDay} 最高价: <span class="high-price">${stock.highPrice.toFixed(2)}</span></div>
        `;
            stockBox_big.innerHTML = `
            <div class="stock-info">${stock.name} (${stock.code})</div>
            <div class="stock-prices">${formattedLastTradingDay} 收盘价: ${stock.closePrice.toFixed(2)} | ${formattedNextTradingDay} 最高价: <span class="high-price">${stock.highPrice.toFixed(2)}</span></div>
        `;

            // 添加点击事件
            stockBox_top.onclick = () => {
                const params = new URLSearchParams({
                    name: stock.name,
                    code: stock.code,
                    closePrice: stock.closePrice.toFixed(2),
                    highPrice: stock.highPrice.toFixed(2)
                });
                location.href = `main.html?${params.toString()}`; // 当前页面跳转
                // window.open(`main.html?${params.toString()}`, '_blank'); // 新页面打开
            };
            stockBox_bottom.onclick = () => {
                const params = new URLSearchParams({
                    name: stock.name,
                    code: stock.code,
                    closePrice: stock.closePrice.toFixed(2),
                    highPrice: stock.highPrice.toFixed(2)
                });
                location.href = `main.html?${params.toString()}`; // 当前页面跳转
                // window.open(`main.html?${params.toString()}`, '_blank'); // 新页面打开
            };
            stockBox_big.onclick = () => {
                const params = new URLSearchParams({
                    name: stock.name,
                    code: stock.code,
                    closePrice: stock.closePrice.toFixed(2),
                    highPrice: stock.highPrice.toFixed(2)
                });
                location.href = `main.html?${params.toString()}`; // 当前页面跳转
                // window.open(`main.html?${params.toString()}`, '_blank'); // 新页面打开
            };

            // 将 stock-box 添加到容器中
            container_top.appendChild(stockBox_top);
            container_bottom.appendChild(stockBox_bottom);
            container_big.appendChild(stockBox_big)
        });
    }

    // function dealWebData(stockData) {//三个地方需要填充
    //     const warning_container_top = document.getElementById('warning_top');
    //     const warning_stockBoxes_top = warning_container_top.getElementsByClassName('stock-box');
    //
    //     const warning_container_bottom = document.getElementById('warning_bottom');
    //     const warning_stockBoxes_bottom = warning_container_bottom.getElementsByClassName('stock-box');
    //
    //     const warning_container_big = document.getElementById('warningContainer-big');
    //     const warning_stockBoxes_big = warning_container_big.getElementsByClassName('stock-box');
    //     // 填充股票数据
    //     for (let i = 0; i < stockData.length; i++) {
    //         const stock = stockData[i];
    //         const warning_stockBox_top = warning_stockBoxes_top[i];
    //         const warning_stockBox_bottom = warning_stockBoxes_bottom[i];
    //         const warning_stockBox_big = warning_stockBoxes_big[i];
    //         const formattedNextTradingDay = formatDate(stock.nextTradingDay);
    //         const formattedLastTradingDay = formatDate(stock.lastTradingDay);
    //         warning_stockBox_top.innerHTML = `
    //         <div class="stock-info">${stock.name} (${stock.code})</div>
    //         <div class="stock-prices">${formattedLastTradingDay} 收盘价: ${stock.closePrice.toFixed(2)} | ${formattedNextTradingDay} 最高价: <span class="high-price">${stock.highPrice.toFixed(2)}</span></div>
    //     `
    //         warning_stockBox_bottom.innerHTML = `
    //         <div class="stock-info">${stock.name} (${stock.code})</div>
    //         <div class="stock-prices">${formattedLastTradingDay} 收盘价: ${stock.closePrice.toFixed(2)} | ${formattedNextTradingDay} 最高价: <span class="high-price">${stock.highPrice.toFixed(2)}</span></div>
    //     `
    //         warning_stockBox_big.innerHTML = `
    //         <div class="stock-info">${stock.name} (${stock.code})</div>
    //         <div class="stock-prices">${formattedLastTradingDay} 收盘价: ${stock.closePrice.toFixed(2)} | ${formattedNextTradingDay} 最高价: <span class="high-price">${stock.highPrice.toFixed(2)}</span></div>
    //     `;
    //         warning_stockBox_top.onclick = () => {
    //             const params = new URLSearchParams({
    //                 name: stock.name,
    //                 code: stock.code,
    //                 closePrice: stock.closePrice.toFixed(2),
    //                 highPrice: stock.highPrice.toFixed(2)
    //             });
    //             location.href = `main.html?${params.toString()}`;/*当前页面*/
    //             // window.open(`main.html?${params.toString()}`, '_blank');/*新页面*/
    //         };
    //         warning_stockBox_bottom.onclick = () => {
    //             const params = new URLSearchParams({
    //                 name: stock.name,
    //                 code: stock.code,
    //                 closePrice: stock.closePrice.toFixed(2),
    //                 highPrice: stock.highPrice.toFixed(2)
    //             });
    //             location.href = `main.html?${params.toString()}`;/*当前页面*/
    //             // window.open(`main.html?${params.toString()}`, '_blank');/*新页面*/
    //         };
    //         warning_stockBox_big.onclick = () => {
    //             const params = new URLSearchParams({
    //                 name: stock.name,
    //                 code: stock.code,
    //                 closePrice: stock.closePrice.toFixed(2),
    //                 highPrice: stock.highPrice.toFixed(2)
    //             });
    //             location.href = `main.html?${params.toString()}`;/*当前页面*/
    //             // window.open(`main.html?${params.toString()}`, '_blank');/*新页面*/
    //         };
    //     }
    // }




    // 格式化日期为 "MM-DD"
    function formatDate_(dateString) {
        const date = new Date(dateString);
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        return `${month}-${day}`;
    }

    // 后台返回的格式是 20240608 这样的 调用之前的函数会出问题
    function formatDate(dateString) {
        dateString = "" + dateString
        // 提取年份、月份和日期
        let year = parseInt(dateString.substring(0, 4));
        let month = parseInt(dateString.substring(4, 6)) - 1; // 月份从0开始
        let day = parseInt(dateString.substring(6, 8));

        let date = new Date(year, month, day);
        const monthStr = (date.getMonth() + 1).toString().padStart(2, '0');
        const dayStr = date.getDate().toString().padStart(2, '0');
        return `${monthStr}-${dayStr}`;
    }

});

let interval1=1500;//两次滚动之间的时间间隔
let stepsize1=$(window).height()*0.125;//滚动一次的长度，必须是行高的倍数,这样滚动的时候才不会断行
// console.log($(window).height())
let scrollspeed1="slow";//可选("slow", "normal", or "fast")，或者滚动动画时长的毫秒数
let objInterval1=null;//上边这些都是滚动的参数
//启动定时器，开始滚动
function StartScroll1(){
    objInterval1=setInterval("verticalloop1()",interval1);
}
//清除定时器，停止滚动
function StopScroll1(){
    window.clearInterval(objInterval1);
}
//控制滚动
function verticalloop1(){
//判断是否上部内容全部移出显示区域
//如果是，从新开始;否则，继续向上移动
    let num = document.getElementById('warning_top').children.length;
    // console.log(num)
    if($("#warning_content").scrollTop()>=$("#warning_top").outerHeight()){
        $("#warning_content").scrollTop($(window).height*0.125*num+"px");
    }
//使用jquery创建滚动时的动画效果
    $("#warning_content").animate({"scrollTop" : $("#warning_content").scrollTop()+stepsize1 +"px"},scrollspeed1,function(){
    });
}